/*
 *  jOTR - Java Off-The-Record Messaging Library
 *  Copyright (C) 2007-2008 Markus Karnik
 *
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 3 of the License, 
 *  or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along 
 *  with this program; if not, see <http://www.gnu.org/licenses/>.
 *  
 */
package de.karnik.libjotr;

import java.math.BigInteger;

import de.karnik.helper.ArrayFunctions;

/**
 * This class implements the Multi Precision Integer data type. It stores on MPI value an servers 
 * with common functions for this data type.<br><br>
 * 
 * See OTR documentation for this data type.
 * 
 * @author Markus Karnik - markus.karnik@my-design.org
 * @version 1.0
 * @since 1.0
 */
public class JotrMpi implements JotrConstants {

	/**
	 * The integer value of this object.
	 */
	private BigInteger value = null;
	/**
	 * The MPI value of this object.
	 */
	private byte[] mpi = null;

	/**
	 * Constructs a MPI object from the given MPI value.
	 * 
	 * @param value
	 */
	public JotrMpi( byte[] value ) {
		setValue( value );
	}
	
	/**
	 * Constructs a MPI object from the given  integer value.
	 * 
	 * @param value
	 */
	public JotrMpi( BigInteger value ) {
		setValue( value );
	}

	/**
	 * Returns the value in MPI format.
	 * 
	 * @return The value in MPI format.
	 */
	public byte[] getValueAsByteArray() {
		return mpi;
	}

	/**
	 * Returns the value as integer.
	 * 
	 * @return The value as integer.
	 */
	public BigInteger getValueAsBigInteger() {
		return value;
	}

	/**
	 * Sets the MPI with a MPI value.
	 * 
	 * @param value The MPI value to set.
	 */
	public void setValue( byte[] value ) {
		
		if( value != null && value.length  > 0 ) {
		
			byte[] temp =  ArrayFunctions.serialize( value );
			this.value = new BigInteger( 1, temp );
			this.mpi = ArrayFunctions.addBigEndianLengthHeader( INT_BYTE_LENGTH, temp );
		} else {
			this.value = BigInteger.ZERO;
			this.mpi = new byte[] { 0x00, 0x00, 0x00, 0x01, 0x00 };
		}
	}	
	
	/**
	 * Sets the MPI with a integer value.
	 * 
	 * @param value The integer value to set.
	 */
	public void setValue( BigInteger value ) {
		setValue( value.toByteArray() );
	}
}
